﻿using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;

namespace EfLearn.Ext
{
    public static class ModelExt
    {
        public static void AdjustOracleDefaultAction(this ModelBuilder modelBuilder)
        {
            foreach (var item in modelBuilder.Model
                .GetEntityTypes()
                .SelectMany(t => t.GetProperties())
                .Where(p => p.ClrType == typeof(string))
                .Select(p => new
                {
                    p.ClrType,
                    p.Name,
                    Pb = modelBuilder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name),
                    MaxLength = p.GetMaxLength()
                }))
            {
                item.Pb.HasColumnName(item.Name.ToLower());
                if (item.ClrType == typeof(DateTime?))
                {
                    item.Pb.HasColumnType("date");
                }
                else
                if (item.Name == "Discriminator")
                    item.Pb.HasMaxLength(100);
                // ReSharper disable once PossibleInvalidOperationException
                else if (item.ClrType == typeof(string) && item.MaxLength == null)
                    item.Pb.HasMaxLength(2000);
            }
        }

        public static void AdjustDbDefautAction(this ModelBuilder modelBuilder)
        {
            foreach (var mutableEntityType in modelBuilder.Model.GetEntityTypes())
            {
                if (mutableEntityType.ClrType == null)
                    continue;
                if (mutableEntityType.ClrType.GetCustomAttribute<TableAttribute>() == null)
                    mutableEntityType.SetTableName(mutableEntityType.ClrType.Name.ToLower());

                //foreach (var foreignKey in mutableEntityType.GetForeignKeys())
                //{
                //    var canCascadeDelete = foreignKey.Properties[0]?.PropertyInfo?.GetCustomAttributes<ForeignKeyReferenceAttribute>()?.SingleOrDefault();
                //    foreignKey.DeleteBehavior = canCascadeDelete?.DeleteBehavior ?? DeleteBehavior.Restrict;
                //}
            }
        }
    }
}